package com.baobao.service;

import com.baobao.dao.AddressDAO;
import com.baobao.domain.Address;

import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * Spring service that handles CRUD requests for Address entities
 * 
 */

@Service("AddressService")
@Transactional
public class AddressServiceImpl implements AddressService {

	/**
	 * DAO injected by Spring that manages Address entities
	 * 
	 */
	@Autowired
	private AddressDAO addressDAO;

	/**
	 * Instantiates a new AddressServiceImpl.
	 *
	 */
	public AddressServiceImpl() {
	}

	/**
	 * Load an existing Address entity
	 * 
	 */
	@Transactional
	public Set<Address> loadAddresss() {
		return addressDAO.findAllAddresss();
	}

	/**
	 * Save an existing Address entity
	 * 
	 */
	@Transactional
	public void saveAddress(Address address) {
		Address existingAddress = addressDAO.findAddressByPrimaryKey(address.getPhone(), address.getBanjiId());

		if (existingAddress != null) {
			if (existingAddress != address) {
				existingAddress.setPhone(address.getPhone());
				existingAddress.setBanjiId(address.getBanjiId());
				existingAddress.setImgUrl(address.getImgUrl());
			}
			address = addressDAO.store(existingAddress);
		} else {
			address = addressDAO.store(address);
		}
		addressDAO.flush();
	}

	/**
	 * Return a count of all Address entity
	 * 
	 */
	@Transactional
	public Integer countAddresss() {
		return ((Long) addressDAO.createQuerySingleResult("select count(*) from Address o").getSingleResult()).intValue();
	}

	/**
	 * Return all Address entity
	 * 
	 */
	@Transactional
	public List<Address> findAllAddresss(Integer startResult, Integer maxRows) {
		return new java.util.ArrayList<Address>(addressDAO.findAllAddresss(startResult, maxRows));
	}

	/**
	 * Delete an existing Address entity
	 * 
	 */
	@Transactional
	public void deleteAddress(Address address) {
		addressDAO.remove(address);
		addressDAO.flush();
	}

	/**
	 */
	@Transactional
	public Address findAddressByPrimaryKey(String phone, String banjiId) {
		return addressDAO.findAddressByPrimaryKey(phone, banjiId);
	}
	
	/**
	 * 根据phone查找address列表
	 */
	@Transactional
	public Set<Address> findAddressByPhone(String phone){
		return addressDAO.findAddressByPhone(phone);
	}
	
	/**
	 *  根据banjiId查找address列表
	 */
	@Transactional
	public Set<Address> findAddressByBanjiId(String banjiId){
		return addressDAO.findAddressByBanjiId(banjiId);
	}
}
